package com.tiantianyuegou.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.tiantianyuegou.R;
import com.tiantianyuegou.http.ApiDefine;
import com.tiantianyuegou.http.SPHelper;
import com.tiantianyuegou.util.LoadingDialog;
import com.tiantianyuegou.util.NetworkUtils;
import com.tiantianyuegou.util.Tools;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * 完善用户资料并注册
 * Created by huyang on 2016/1/5 0005.
 */
public class UserInfoActivity extends BaseActivity implements View.OnClickListener, TextWatcher {

    private EditText edt_name, edt_IDcard, edt_email;
    private Button btn_success;
    private TextView tv_register_xieyi;
    private String location;//所在地区
    private String name;//真实姓名
    private String address;//详细地址
    private String TAG = "UserInfoActivity";
    private LoadingDialog loadingDialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_userinfo);
        Tools.changeSystemBar(this);
        setTitle(R.string.userinfo_title);
        initViews();
    }

    @Override
    public void findViewByIds() {
        edt_name = (EditText) findViewById(R.id.edt_name);
        edt_IDcard = (EditText) findViewById(R.id.edt_cardID);
        edt_email = (EditText) findViewById(R.id.edt_email);

//        edt_code = (EditText) findViewById(R.id.edt_invitation_code);
//        tv_register_xieyi = (TextView) findViewById(R.id.tv_register_xieyi);
        btn_success = (Button) findViewById(R.id.btn_success);
    }

    @Override
    public void initListener() {
        edt_name.addTextChangedListener(this);
        edt_email.addTextChangedListener(this);
        edt_IDcard.addTextChangedListener(this);
// TODO 模拟数据存入sp,当接口完成后完成真正的网络请求，现在模拟数据
        loadingDialog = new LoadingDialog(this);
//        tv_register_xieyi.setOnClickListener(this);
        btn_success.setOnClickListener(this);
    }

    @Override
    public void initData() {
        Intent intent = getIntent();
         phone = intent.getStringExtra("phone");
        password = intent.getStringExtra("password");

    }

    private void login() {
//        TODO 换成真正的联网请求进行请求数据
        RequestParams params = new RequestParams();
        params.addBodyParameter("account", phone);
        params.addBodyParameter("password", password);
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.LOGIN, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> response) {
                loadingDialog.dismiss();
                Log.e(TAG, "onSuccess response.result" +
                        response.result);
                if (TextUtils.isEmpty(response.result)) {
                    showMsg("获取失败");
                    return;
                } else {
                    try {
                        JSONObject jsonObject = new JSONObject(response.result);
                        String code = jsonObject.getString("code");
                        if (code.equalsIgnoreCase("100")) {
                            String tmId = jsonObject.getString("tm_id");
                            String tmPhone = jsonObject.getString("tm_mobile");
                            /*if (!jsonObject.toString().contains("tmAvatar\":null")) {
                                String tmAvater = jsonObject.getString("tmAvatar");
                            }*/
                            String tmName = jsonObject.getString("tm_name");
                            SPHelper.setTmId(tmId);
                            System.out.println("---------LoginActivity:tmid" + tmId);
                        } else if (code.equalsIgnoreCase("101")) {
                            showMsg("登陆失败");
                        } else if (code.equalsIgnoreCase("103")) {
                            showMsg("账号不存在");
                            loadingDialog.dismiss();
                        } else if (code.equalsIgnoreCase("104")) {
                            showMsg("密码错误");
                            loadingDialog.dismiss();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                        showMsg("登录失败");
                        loadingDialog.dismiss();
                    }
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                loadingDialog.dismiss();
                showMsg("当前网络不可用，请检查网络设置");
            }
        });
    }

    private String phone;
    private String password;
    private String account;
    private String vcode;
    private String payPassword;

    public void register() {
        name = edt_name.getText().toString().trim();
        location = edt_IDcard.getText().toString().trim();
        address = edt_email.getText().toString().trim();
        Log.e(TAG, name + location + address);
        if (!NetworkUtils.isNetworkAvailable(this)) {
            showMsg("请检查您的网络");
            return;
        }
        if (TextUtils.isEmpty(name)) {
            showMsg("请输入您的真实姓名");
            return;
        }
        if (TextUtils.isEmpty(location)) {
            showMsg("请输入您的地区");
            return;
        }
        if (TextUtils.isEmpty(address)) {
            showMsg("请输入你的详细地址");
        }

     /*   if (!IDVerifyUtils.IDCardValidate(IDcard.toLowerCase())) {
            showMsg("身份证号码格式错误");
            return;
        }
        if (TextUtils.isEmpty(email)) {
            showMsg("请输入您的邮箱");
            return;
        }
        if (!StringUtils.checkEmail(email)) {
            showMsg("邮箱格式错误");
            return;
        }*/
        final Intent intent = getIntent();
        phone = intent.getStringExtra("phone");
         vcode = intent.getStringExtra("vcode");
        password = intent.getStringExtra("password");
        account = intent.getStringExtra("account");
        payPassword = intent.getStringExtra("paypassword");
        Log.e(TAG, phone + "," + vcode + "," + password);


        loadingDialog.showDialog();
        loadingDialog.setMsg("正在注册");
//        ToastUtils.showToast(this,"注册成功");
//        login();
//        Intent intent1 = new Intent(UserInfoActivity.this, MainActivity.class);
//        startActivity(intent1);
//        finish();
//        TODO 需换成真正的联网请求进行注册
        RequestParams params = new RequestParams();
        params.addBodyParameter("account",account);
        params.addBodyParameter("phone", phone);
        params.addBodyParameter("password", password);
        params.addBodyParameter("paypassword",payPassword);
        params.addBodyParameter("name", name);
        params.addBodyParameter("province",String.valueOf(1));   //省 province
        params.addBodyParameter("city",String.valueOf(1));          // 市 city
        params.addBodyParameter("county",String.valueOf(1)); //区county
        params.addBodyParameter("address",String.valueOf(1)); //街道address
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.REGISTER, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> response) {
                loadingDialog.dismiss();
                Log.e(TAG, "onSuccess response.result  "
                        + response.result);
                if (TextUtils.isEmpty(response.result)) {
                    showMsg("获取失败");
                }
                try {
                    JSONObject jsonObject = new JSONObject(response.result);
                    String code = jsonObject.getString("code");
                    if (code.equalsIgnoreCase("100")) {
                        SPHelper.setPassword(password);//保存用户的密码
                        login();
                        Intent intent1 = new Intent(UserInfoActivity.this, MainActivity.class);
                        startActivity(intent1);
                        finish();
                    } else if (code.equalsIgnoreCase("103")) {
                        showMsg("省市区参数有误");
                    } else if (code.equalsIgnoreCase("105")){
                        showMsg("该手机号码已被注册");
                    }else {
                        String msg = jsonObject.getString("message");
                        showMsg(msg);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    loadingDialog.dismiss();
                    showMsg("获取失败");
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                loadingDialog.dismiss();
                showMsg("当前网络不可用，请检查网络设置");
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_success:
                register();
                Log.e(TAG, "点击了注册注册注册注册注册注册注册注册");
                break;
            case R.id.tv_register_xieyi:
                Intent intent = new Intent(this, WebActivity.class);
                intent.putExtra("type", "4");
                startActivity(intent);
                break;
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {

        String name = edt_name.getText().toString();
        String idCard = edt_IDcard.getText().toString();
        String email = edt_email.getText().toString();
        if (name != null && !"".equals(name) && idCard != null && !"".equals(idCard) && email != null && !"".equals(email)) {
            btn_success.setAlpha(1.0f);
            btn_success.setEnabled(true);
        } else {
            btn_success.setAlpha(0.5f);
            btn_success.setEnabled(false);
        }


    }
}
